package com.huluobo.base.view;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public abstract class BaseFragment<V, P extends BasePresenter<V>> extends Fragment {

    protected P presenter;
    protected View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(bindLayoutId(), null);
        return view;
    }

    protected abstract int bindLayoutId();

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
        if (presenter != null) {
            presenter.attachView((V) this);
        }
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        if (event == null || TextUtils.isEmpty(event.getTarget())) return;
        //判断是否为当前页面
        if (event.getTarget().equals(getClass().getSimpleName())) {
            handEvent(event);
        }
    }

    protected void handEvent(Event event) {

    }

    protected abstract void initData();

    protected abstract void initView();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.disAttach();
        }
    }

    public <T extends View> T findViewById(int id) {
        return view.findViewById(id);
    }
}
